package com.prdiot.poetry.controller;

import com.prdiot.poetry.domains.Author;
import com.prdiot.poetry.domains.Poems;
import com.prdiot.poetry.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.List;
import java.util.Map;
import java.util.Random;

@Controller
public class AuthorsController {

    @Autowired
    AuthorService authorService;

    @Autowired
    PoemsService poemsService;

    @Autowired
    TagsService tagsService;

    @Autowired
    MingjuService mingjuService;

    @Autowired
    ChengyuService chengyuService;

    @GetMapping("/authors")
    public String authors(Model model, String page){

        int curPage = 1;
        try{
            curPage = Math.abs(Integer.valueOf(page));
            if (curPage<1){
                curPage = 1;
            }
        }catch (Exception exception){
            curPage = 1;
        }

        Page<Author> allAuthors = authorService.getAllAuthors(curPage);
        List<Author> authorList = allAuthors.getContent();
        for (Author author:authorList) {
            author.setDynastyId(poemsService.getDynastyIdByName(author.getDynasty()));
        }
        model.addAttribute("authorList", authorList);
        model.addAttribute("page", curPage);
        model.addAttribute("pageCount", allAuthors.getTotalPages());
        model.addAttribute("tagList",tagsService.getTagsOrderByPoemCount(100));
        model.addAttribute("themeList",mingjuService.getMingjuTheme());
        model.addAttribute("mingjuList",mingjuService.getRandMingju());
        model.addAttribute("chengyuList",chengyuService.getRandPoetry());
        return "authors";
    }

    @GetMapping("/author/{authorId}")
    public String author(Model model, @PathVariable("authorId") String authorId){
        Author author = authorService.findByAuthorId(authorId);
        if (author != null){
            author.setDynastyId(poemsService.getDynastyIdByName(author.getDynasty()));
            model.addAttribute("author",author);
            model.addAttribute("authorRandPoems", poemsService.attachTag(poemsService.getRandPoetryByAuthorId(authorId)));
        }
        model.addAttribute("tagList",tagsService.getTagsOrderByPoemCount(100));
        model.addAttribute("themeList",mingjuService.getMingjuTheme());
        model.addAttribute("mingjuList",mingjuService.getRandMingju());
        model.addAttribute("chengyuList",chengyuService.getRandPoetry());
        return "authorDetails";
    }


}
